using System;
using System.Resources;
using EnvDTE;
using Microsoft.Practices.RecipeFramework;
using VSSDKAssist.Assets.Actions.Base;
using VSSDKAssist.Assets.Helpers;
using VSSDKAssist.Recipes.Common.Helpers;

namespace VSSDKAssist.Recipes.Common.Actions
{
	/// <summary>
	/// Action that adds a bitmap entry to a resx file
	/// </summary>
	public class AddBitmapEntryToResxAction : ActionBase
	{
		private ProjectItem resxProjectItem;

		/// <summary>
		/// Gets or sets the RESX project item.
		/// </summary>
		/// <value>The RESX project item.</value>
		[Input(Required = true)]
		public ProjectItem ResxProjectItem
		{
			get { return resxProjectItem; }
			set { resxProjectItem = value; }
		}

		private ProjectItem bitmapProjectItem;

		/// <summary>
		/// Gets or sets the bitmap project item.
		/// </summary>
		/// <value>The bitmap project item.</value>
		[Input(Required = true)]
		public ProjectItem BitmapProjectItem
		{
			get { return bitmapProjectItem; }
			set { bitmapProjectItem = value; }
		}

		private string bitmapResourceId;

		/// <summary>
		/// Gets or sets the bitmap resource id.
		/// </summary>
		/// <value>The bitmap resource id.</value>
		[Input(Required = true)]
		public string BitmapResourceId
		{
			get { return bitmapResourceId; }
			set { bitmapResourceId = value; }
		}

		/// <summary>
		/// Called when [execute].
		/// </summary>
		protected override void OnExecute()
		{
			string resxFileName = 
				this.ResxProjectItem.Properties.Item("FullPath").Value.ToString();

			ResXDataNode node = ResxHelper.GetResxDataNodeById(
				this.Site as IServiceProvider,
				resxFileName,
				this.BitmapResourceId);

			if(node != null)
			{
				string bitmapFileName = VSIPHelper.GetRelativePath(
					this.bitmapProjectItem.ContainingProject, 
					this.bitmapProjectItem);

				ResXFileRef fileRef = new ResXFileRef(
					bitmapFileName, 
					ResxHelper.GetResxType(bitmapFileName));
				
				ResXDataNode newNode = new ResXDataNode(this.bitmapResourceId, fileRef);
				
				ResxHelper.UpdateResxEntry(
					this.ResxProjectItem, 
					newNode, 
					this.BitmapResourceId);
			}
			else
			{
				ResxHelper.AppendBitmapResxEntry(
					this.ResxProjectItem,
					this.BitmapProjectItem, 
					this.BitmapResourceId);
			}
		}
	}
}